package org.epam.szhuk.greenway.activity;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.epam.szhuk.greenway.R;
import org.epam.szhuk.greenway.customview.CustomMapView;
import org.epam.szhuk.greenway.klymanovs.PollutionMatrix;
import org.epam.szhuk.greenway.klymanovs.Polygons;
import org.epam.szhuk.greenway.klymanovs.Spot;
import org.epam.szhuk.greenway.klymanovs.TypeOfShit;
import org.epam.szhuk.greenway.model.StoredGeoPoint;
import org.epam.szhuk.greenway.util.FileProcessor;
import org.epam.szhuk.greenway.util.GeoDataProcessor;
import org.epam.szhuk.greenway.util.Preferences;
import org.epam.szhuk.overlay.PathOverlay;
import org.epam.szhuk.overlay.PointerOverlay;
import org.epam.szhuk.overlay.PolygonOverlay;

import com.google.android.maps.GeoPoint;
//import com.google.android.maps.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomButtonsController;
import android.widget.ZoomControls;

/**
 * 
 * @author Sergii Zhuk
 *
 */
public class RecordedPathActivity extends MapActivity  {
	
   private static final String TAG = "RecordedPathActivity";

    //----Map data:
    private int mapZoom=17;
    private List<Overlay> mapOverlays;
	private Projection projection;
	private MapController mapController;
	private CustomMapView customMapView;
    RelativeLayout layoutSpeedData;
    List<PollutionMatrix> pmList=new ArrayList<PollutionMatrix>();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_recorded_path_map); 
	    Bundle extras = getIntent().getExtras();
	    List<List<StoredGeoPoint>> multipleStoredGeoPointLists=null; 
		if (extras != null) {
			multipleStoredGeoPointLists = (List<List<StoredGeoPoint>>)extras.getSerializable("multipleStoredGeoPointLists");
		}
		else{
			Log.e(TAG,TAG+" started without proper bundle extras");
			myToast(TAG+" started without proper bundle extras");
		}
		customMapView = (CustomMapView) findViewById(R.id.mapview1);// Creating an instance
		customMapView.setBuiltInZoomControls(true);
		prepareMap(multipleStoredGeoPointLists);
		setPollutions();
		paintPathOverlays(multipleStoredGeoPointLists);
   }
   
   
   private void prepareMap(List<List<StoredGeoPoint>> multipleStoredGeoPointLists){
	    //storedGeoPointsList=GeoDataProcessor.getGeoPointsForFile(RecordedPathActivity.this,pathToFile);
	    if((multipleStoredGeoPointLists==null)||(multipleStoredGeoPointLists.size()==0)){
			Log.e(TAG, "multipleStoredGeoPointLists is empty or 0, unable to show position at the map");
			myToast(getResources().getString(R.string.cant_get_info_for_selected_probably_location_na));
			RelativeLayout layoutNoCoordinatesAvailable= (RelativeLayout) findViewById(R.id.layoutNoCoordinatesAvailable);
			layoutNoCoordinatesAvailable.setVisibility(View.VISIBLE);
		}
		else{
			customMapView = (CustomMapView) findViewById(R.id.mapview1);// Creating an instance
			customMapView.setBuiltInZoomControls(true);
		
			StoredGeoPoint storedGP=multipleStoredGeoPointLists.get(0).get(0);
			GeoPoint gP = new GeoPoint(storedGP.getLat(), storedGP.getLon());
				
			mapController = customMapView.getController();
			mapController.setCenter(gP);
			mapController.setZoom(mapZoom);
			mapOverlays = customMapView.getOverlays();
			projection = customMapView.getProjection();
			
			customMapView.setVisibility(View.VISIBLE);
			RelativeLayout layoutNoCoordinatesAvailable= (RelativeLayout) findViewById(R.id.layoutNoCoordinatesAvailable);
			layoutNoCoordinatesAvailable.setVisibility(View.GONE);
		}
   }
   
   private void paintPathOverlays(List<List<StoredGeoPoint>> multipleStoredGeoPointLists){
	   if((multipleStoredGeoPointLists!=null)||(multipleStoredGeoPointLists.size()!=0)){
	   for(int i=0; i<multipleStoredGeoPointLists.size(); i++){
			PathOverlay pathOverlay = new PathOverlay(multipleStoredGeoPointLists.get(i),projection,customMapView.getMaxZoomLevel(),mapZoom);
			mapOverlays.add(pathOverlay);		
	   }
	   customMapView.invalidate(); 
	   }
   }
   
   private void flushMap(){
	   if((mapOverlays!=null)&&(!mapOverlays.isEmpty())){
            mapOverlays.clear();
  	        customMapView.getOverlays().clear();
  	        customMapView.invalidate();
	   } 
	   mapOverlays=null;
	   if(customMapView!=null){
		   customMapView.destroyDrawingCache();

	   }
	   projection=null;
	   mapController=null;
    }
   
	@Override
	protected void onPause(){
		super.onPause();
	}
	
	@Override
	protected void onResume(){
		super.onResume();
	
	}	   
   
	private void myToast(String text){
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
    private void setPollutions(){
		ArrayList<ArrayList<Spot>> mapAreas = new ArrayList<ArrayList<Spot>>();
		ArrayList<TypeOfShit> diffShit = new ArrayList<TypeOfShit>();
	
		diffShit.add(new TypeOfShit(0.2, "#00008B", "raw/pollution_polygons"));
		diffShit.add(new TypeOfShit(0.1, "#FF8C00", "raw/pollution_polygons_co2"));
		for (TypeOfShit shit : diffShit) {
			try {
				int resId=getResources().getIdentifier(shit.getPath(),null,this.getPackageName());
				InputStream is = getResources().openRawResource(resId);
				
				Gson gson = new Gson();
				Reader reader = new InputStreamReader(is);
				
				Polygons polygons = gson.fromJson(reader,Polygons.class);
				mapAreas = polygons.getMapAreas();
				PollutionMatrix pm = polygons.getPollutionMatrix();
				if (mapAreas != null) {
					for (int i = 0; i < mapAreas.size(); i++) {
							List<Spot> spotList = mapAreas.get(i);
							Overlay polygonOverlay=new PolygonOverlay(spotList, shit.getColor(), shit.getOpacityLevel(), pm,projection);
							mapOverlays.add(polygonOverlay);
						}
				}
				pmList.add(pm);
				
			} catch (JsonSyntaxException e) {
				Log.e(TAG,"",e);
			} catch (JsonIOException e) {
				Log.e(TAG,"",e);
			}
		} 
		customMapView.invalidate();
    }

}